package com.me.controllers;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.me.Utils.AlipayConfig;
import com.me.annotation.Authorize;
import com.me.annotation.Inject;
import com.me.model.Order;
import com.me.model.viewmodel.AlipayViewModel;
import com.me.model.viewmodel.CartViewModel;
import com.me.model.viewmodel.OrderViewModel;
import com.me.model.viewmodel.PayViewModel;
import com.me.service.GoodsService;
import com.me.service.OrderService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class OrderController extends Controller {
	@Inject private GoodsService gserv;
	@Inject private OrderService oserv;

	@Inject
	public OrderController(HttpServletRequest req, HttpServletResponse resp) {
		super(req, resp);
	}

	@Override
	public String index(String arg) {
		return myorder(arg);
	}

	@Authorize
	public String onLogin(String arg) {
		oserv.checkCartExist(getSessionUser());
		updateCartTotal();
		return home();
	}

	@Authorize
	public String buy() {
		oserv.addToOrder(getSessionUser(),getParam("goodsid"));
		print(String.format("{\"state\":\"%s\",\"total\":\"%d\"}", "ok", updateCartTotal()));
		return stayPage();
	}

	@Authorize
	public String reduce() {
		oserv.reduceFromCart(getSessionUser(),getParam("goodsid"));

		print(String.format("{\"state\":\"%s\",\"total\":\"%d\"}", "ok", updateCartTotal()));
		return stayPage();
	}

	@Authorize
	public String delete() {
		oserv.deleteFromCart(getSessionUser(),getParam("goodsid"));
		print(String.format("{\"state\":\"%s\",\"total\":\"%d\"}", "ok", updateCartTotal()));
		return stayPage();
	}

	@Authorize
	public String cart(String arg) {
		CartViewModel viewModel = new CartViewModel();
		viewModel.setOis(oserv.getUserCart(getSessionUser()));

		return view(viewModel);
	}

	@Authorize
	public String pay(String arg) {
		PayViewModel viewModel = new PayViewModel(getSessionUser(),oserv.getUnCommitOrder(getSessionUser().getId()));

		return view("pay", viewModel);
	}

	@Authorize
	public String pay() {
		PayViewModel viewModel = (PayViewModel) Model;
		Order o = oserv.getUnCommitOrder(getSessionUser().getId());
		oserv.PreparePay(u, o);

		o.setName(viewModel.name);
		o.setPhone(viewModel.phone);
		o.setAddress(viewModel.address);

		setReqAttr("WIDout_trade_no", o.getId());
		setReqAttr("WIDtotal_amount", o.getTotal());
		setReqAttr("WIDsubject","蛋糕店订单");

		updateCartTotal();

		return view("alipay",null);
	}

	private int updateCartTotal(){
		int total = 0;
		if (getSessionUser() != null) {
			total = oserv.getCartNum(getSessionUser());
			setSessionAttr("buyTotal", total);
		} else {
			setSessionAttr("buyTotal", null);
		}
		return total;
	}

	@Authorize
	public String paysuccess(String arg) {
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = req.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		try {
			boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
			if (signVerified) {
				String id = getParam("out_trade_no");
				oserv.setSuccessPay(id);
				return view("paysuccess", new AlipayViewModel(
						id,
						getParam("trade_no"),
						getParam("total_amount")

				));
			} else {
				return redirectToAction("pay");
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Authorize
	public String myorder(String arg) {
		OrderViewModel viewModel = new OrderViewModel();
		viewModel.setOrders(oserv.getOrders(getSessionUser()));

		return view("myorder", viewModel);
	}

}
